
var sto;

Ext.onReady(function() {
    
    // 创建一个类似 JavaBean 的东西
    Ext.define("Business", {
	extend : "Ext.data.Model",
	fields: ["id", "name", "type", "area", "image", "context",
	         "pub_time", "beg_time", "end_time", "uses", "score", "status"]
    });
    
    // 定义一个数据代理，代理方式为Ajax，渲染方式为json
    var mproxy = new Ext.data.proxy.Ajax({
	url : "/QuickLifeServer/WebCouponManageAction",
	idparam: "busid",
	startParam: "begin",
	limitParam: "need",
	timerout: 20000,
	extraParams : {
	    "actionflag" : "getcp",
	    "busid" : Ext.getDom("id").value
	},
	reader: new Ext.data.JsonReader({
	    root : "rtinfos",
	    idProperty: 'id',
	    totalProperty: 'total'
	})
    });
    
    // 定义数据集，使用了 mproxy 这个数据代理
    sto = Ext.create('Ext.data.Store', {
	model : "Business",
	proxy : mproxy,
	pageSize : 10
    });
    
    // 定义表的结构
    var columnModel = [
           {
               text:"优惠名", dataIndex: "name", width: 24,
           },{
               text:"类型", dataIndex: "type", width: 6, renderer: function(value) {
        	   //var types = ["餐饮", "休闲娱乐", "生活服务", "购物", "酒店", "运动健身", "婚庆", "家居装修"];
        	   //return types[value];
        	   if (value == 1) {
        	       return "全城热推";
        	   } else {
        	       return "路过惊喜";
        	   }
               }
           },{
               text:"区域", dataIndex: "area", width: 5, 
               	renderer : function(value, metaData, record, rowIndex, colIndex, store ) {
               	    if (record.get("type") == 2) {
               		return value + "m";
               	    } else {
               		return "全城";
               	    }
               	}
           },{
    	    text: "图片", dataIndex: "image", width: 8, sortable : false,
    	    renderer: function(value) {
    		align : "center";
    		return "<a target='_blank' href='" + value + "'><img src='" + value + "' width=70/></a>"
    	    }
    	}, {
    	    text:"发布时间", dataIndex: "pub_time", width: 10, renderer: function(value) {
    		return value.split(" ")[0];
    	    }
    	},{
    	    text:"开始时间", dataIndex: "beg_time", width: 10, renderer: function(value) {
    		return value.split(" ")[0];
    	    }
    	},{
    	    text:"结束时间", dataIndex: "end_time", width: 10, renderer: function(value) {
    		return value.split(" ")[0];
    	    }
    	},{
    	    text:"使用次数", dataIndex: "uses", width: 6
    	},{
    	    text:"评分", dataIndex: "score",  width: 5
    	},{
    	    header:"状态", dataIndex: "status", width: 7, renderer: function(value) {
    		if (value == 0) {
    		    return "未发布";
    		} else if (value == 1) {
    		    return "已发布";
    		} else if (value == 2) {
    		    return "终止";
    		} else if (value == 3) {
    		    return "活动结束";
    		} else if (value == 4) {
    		    return "已中止";
    		}
    	    }
    	},{
    	    width: 6, 
    	    // 渲染，渲染的参数在API Ext.grid.column.Column 可以看到
    	    renderer: function(value, meta, record, rowIndex, colIndex, store ) {
    		return "<button id='detail' class='button'>详细</button>";
    	    }
    	}, {
    	    width: 6,
    	    renderer: function(value, meta, record) {
    		return "<button id='comment' class='button'>评论</button>";
    	    }
    	}, {
    	    width: 6,
    	 renderer: function(value, meta, record) {
 		return "<button id='push' class='button'>推送</button>";
 	    }
    	}
    ];
    
    // 分布工具栏
    var pageBar = new Ext.PagingToolbar({
	store: sto,
	pageSize: 5,
	displayInfo: true,
	emptyMsg: "没有记录",
    });
    
    // 定义表格
    var mgrid = Ext.create('Ext.grid.GridPanel', {
	store : sto,
	columns: columnModel,
	forceFit: true,
	layout : "fit",
	bbar: pageBar,
	height: window.innerHeight,
	defaults: {
	   height : 60 
	},
	renderTo : Ext.getBody()
    });
    
    // 添加按钮监听， who 就是谁调用的
    mgrid.addListener('cellClick', function(who, td, cellIndex, record, tr, rowIndex, e, eOpts) {
	if (td.lastChild.lastChild.id == "detail") {
	    coupons_detail(record);
	} else if (td.lastChild.lastChild.id == "comment") {
	    coupons_comment(record);
	} else if (td.lastChild.lastChild.id == "push") {
	    push_coupons(record);
	}
    });
    
    // 窗口大小改变监听，使表单可以自动设置大小
    Ext.EventManager.onWindowResize(function(){ 
        mgrid.getView().refresh() 
    });
    
    // 加载数据
    sto.load({
	params: {
	    begin:0,
	    need:10
	},
	callback: function(records, operation, success) {
	}
    });
    
});

/**
 * 显示优惠详细信息
 * @param record 行记录
 */
function coupons_detail(record) {
    // 创建表单项
    var formItems = [
	         {
	             fieldLabel : "优惠名",
	             name : "name",
	             emptyText : "优惠的名称是什么？",
	             allowBlank : false,
	             blankText : "优惠不能没有名字",
	             value : record.get("name")
	         },
	         {
	             xtype: 'radiogroup',
	             fieldLabel: '类型',
	             name : "type",
	             id : "type",
	             listeners : {
	        	 change : function(view, newValue) {
	        	     if (newValue.type == 2) {
	        		view.nextNode("numberfield").setVisible(true); 
	        	     } else {
	        		view.nextNode("numberfield").setVisible(false); 
	        	     }
	        	 }
	             },
	             items: [
	                 {boxLabel: '全城热推', id : "city", name: 'type', inputValue: 1},
	                 {boxLabel: '路过惊喜', id : "passby", name: 'type', inputValue: 2},
	             ]
	         },
	         {
	             xtype : "numberfield",
	             id :"area",
	             name : "area",
	             minValue : 500,
	             value : 1000,
	             maxValue : 10000,
	             fieldLabel : "影响区域(米)",
	             value : record.get("area"),
	             hidden : true
	         },
	         {
	             xtype : "datefield",
	             fieldLabel : "开始时间",
	             value : record.get("beg_time").split(" ")[0],
	             name : "beg_time",
	             allowBlank : false,
	             blankText : "开始时间不得为空",
	             format : "Y-m-d",
	             invalidText : "格式为 '年-月-日"
	         },
	         {
	             xtype : "datefield",
	             fieldLabel : "结束时间",
	             value : record.get("end_time").split(" ")[0],
	             name : "end_time",
	             allowBlank : false,
	             blankText : "结束时间不得为空",
	             format : "Y-m-d",
	             invalidText : "格式为 '年-月-日"
	         },
	         {
	             xtype : "filefield",
	             fieldLabel : "优惠图片",
	             allowBlank : true,
	             name : "image",
	             id : "image",
	             buttonText : "选择图片"
	         },{
	             xtype : "textareafield",
	             emptyText : "优惠的有什么具体内容？",
	             value : record.get("context"),
	             grow : true,
	             allowBlank : false,
	             blankText : "优惠内容不能为空",
	             name : "context",
	             fieldLabel : "优惠内容"
	         }, {
	             xtype : "textfield",
	             value : record.get("status"),
	             readOnly : true,
	             itemId : "cm_status",
	             name: "status",
	             hidden : true
	         }, {
	             xtype : "textfield",
	             value : "优惠修改失败",
	             readOnly : true,
	             itemId : "fail_info",
	             hidden : true
	            
	         }
	];
    
    var submitForm = function(actionflag) {
	       var params = "cpid=" + record.get("id") + 
      		"&actionflag=mdfcp";
	   form_panel.getForm().submit({
	       url: "/QuickLifeServer/WebCouponManageAction?" + params,
	       method: "POST",
	       waitTitle:"请稍候",
	       waitMsg:"正在修改优惠信息。。。",
	       success: function(form, action) {
		   var rt = JSON.parse(action.response.responseText);
		   if (rt.result == "SUCCESS") {
		       sto.reload();
		       detail_dialog.close();
		   } else {
		       Ext.ComponentQuery.query("#fail_info")[0].setValue(rt.rtinfos).setVisible(true);
		   }
	       },
	       failure: function(form, action) {
   		   var rt = JSON.parse(action.response.responseText);
		   if (rt.result == "SUCCESS") {
		       sto.reload();
		       detail_dialog.close();
		   } else {
		       Ext.ComponentQuery.query("#fail_info")[0].setValue(rt.rtinfos).setVisible(true);
		   }
   	       }
	   });
    }
    
    // 实例化按钮
    var formButtons = [
                   {
                	text : "发布",
                	itemId : "publish",
                	listeners : {
                	    click : function() {
                		Ext.ComponentQuery.query("#cm_status")[0].setValue(1);
                		submitForm();
                	    }
                	}
                   },
	           {
	               text : "修改",
	               itemId : "modify",
	               listeners : {
	        	   click : submitForm
	               }
	           }, {
	               text : "中止",
	               itemId : "suspend",
	               listeners : {
	        	   click : function() {
	        	       Ext.ComponentQuery.query("#cm_status")[0].setValue(2);
               			submitForm();
	        	   }
	               }
	           }, {
	               text : "删除",
	               itemId : "delete",
	               handler : function() {
	        	   Ext.Ajax.request({
	        	       url: "/QuickLifeServer/WebCouponManageAction",
	        	       params: {
	        		   cpid: record.get("id"),
	        		   actionflag: "delcp"
	        	       },
	        	       success: function(response) {
	        		   var rt = Ext.decode(response.responseText);
	        		   if (rt.result == "SUCCESS") {
	        		       sto.reload();
	        		       detail_dialog.close();
	        		   } else {
	        		       Ext.ComponentQuery.query("#fail_info")[0].setValue(rt.rtinfos).setVisible(true);
	        		   }
	        	       },
	        	       failure: function(response) {
	        		   var rt = Ext.decode(response.responseText);
	        		   if (rt.result == "SUCCESS") {
	        		       sto.reload();
	        		       detail_dialog.close();
	        		   } else {
	        		       Ext.ComponentQuery.query("#fail_info")[0].setValue(rt.rtinfos).setVisible(true);
	        		   }
	        	       }
	        	   });
	               }
	           }
	];
    
    // 实例化表单
    var form_panel = Ext.create("Ext.form.Panel", {
	autoScroll : true,
	layout : {
	   type : 'vbox',
	   pack : "Even",
	   align : "center"
	},
	defaultType : 'textfield',
	defaults : {
	    width : "60%",
	    style : {
		marginTop : "10px"
	    }
	},
	items : formItems,
	buttons : formButtons
    });
    
    // 实例化窗口
    var detail_dialog = Ext.create("Ext.window.Window", {
	title: "优惠详情",
	items : form_panel,
	layout : 'fit',
	modal: true,
	height : 500, 
	width : 500,
	shadow : "drop",
	shadowOffset : 30
    });
    
    // 初始化数值
    if (record.get("type") == 1) {
	Ext.ComponentQuery.query("#city")[0].setValue(true);
    } else {
	Ext.ComponentQuery.query("#passby")[0].setValue(true);
	Ext.ComponentQuery.query("#area")[0].setVisible(true);
    }
    // 初始化按钮状态
    if (record.get("status") != 1) {
	Ext.ComponentQuery.query("#suspend")[0].disable(false);
    }
    if (record.get("status") > 0) {
	Ext.ComponentQuery.query("#publish")[0].disable(false);
	Ext.ComponentQuery.query("#delete")[0].disable(false);
    }
    
    // 显示窗口
    detail_dialog.show();
    
    // 窗口大小改变监听，使表单可以自动设置大小
    Ext.EventManager.onWindowResize(function(){ 
        grid1.getView().refresh() 
    });
    
}

/**
 * 显示评论列表
 * @param record
 */
function coupons_comment(record) {
    
    // JavaBean对象声明
    Ext.define("Comment", {
	extend: "Ext.data.Model",
	fields: ["user", "comments", "score", "photo", "recording", "video"]
    });
    
    // 实例化数据代理对象
    var mProxy = Ext.create("Ext.data.proxy.Ajax", {
	url: "/QuickLifeServer/WebCouponManageAction",
	pageSize : 7,
	startParam: "begin",
	limitParam: "need",
	params: {
	    actionflag : "getcpcm"
	},
	render: {
	    type: "json",
	    root: "rtinfos"
	}
    });
    
    // 实例化数据集对象
    var sto = Ext.create("Ext.data.Store", {
	model: "Comment",
	proxy : mProxy,
	pageSize : 7
    });
    
    // 实例化表结构，同时跟数据集进行配对
    var cm = [
              {text: "评论者", dataIndex: "user", width: 15},
              {text: "分数", dataIndex: "score", width: 7},
              {text: "评论内容", dataIndex: "comments"},
              {text: "照片", dataIndex: "photo", width:13, sortable: false, renderer: function(value) {
        	  return "<a target='_blank' href='" + value + "'>点击查看</a>";
              }},
              {text: "录音", dataIndex: "recording", width:13, sortable: false, renderer: function(value) {
        	  return "<a target='_blank' href='" + value + "'>点击收听</a>";
              }},
              {text: "视频", dataIndex: "recording", width:13, sortable: false, renderer: function(value) {
        	  return "<a target='_blank' href='" + value + "'>点击观看</a>";
              }}
              ];
    
    // 实例化表的分页工具栏，同时跟数据集进行配对
    var pagingTool = Ext.create("Ext.toolbar.Paging", {
	store: sto,
	emptyMsg: "没有评论",
	displayInfo: true
    });
    
    // 实例化表对象并且显示
    var gridPanel = Ext.create("Ext.grid.GridPanel", {
	store: sto,
	bbar: pagingTool,
	forceFit: true,
	columns : cm
    });
    
    // 实例化窗口并且把表单放到窗口当中
    var dialog = Ext.create("Ext.window.Window", {
	items: gridPanel,
	title: "优惠评论",
	modal: true,
	width: 800,
	height: 600,
	buttons: {
	    text: "关闭",
	    handler: function() {
		dialog.close();
	    }
	}
    });
    
    // 显示窗口
    dialog.show();
    
    // 加载数据
    sto.load({
	params: {
	    begin: 0,
	    need: 7,
	}
    });
    
}

/**
 * 推送优惠
 */
function push_coupons(record) {
 // 表单项创建
    var formItems = [
                 {
                     xtype : "textfield",
                     readOnly : true,
                     fieldLabel : "优惠名称",
                     value: record.get("name"),
                     name: "cpname"
                 },
	         {
	             xtype : "textareafield",
	             emptyText : "推送的有什么具体内容？",
	             grow : true,
	             allowBlank : false,
	             blankText : "推送内容不能为空",
	             name : "msg",
	             fieldLabel : "推送内容"
	         }, {
	             xtype : "textfield",
	             value : "推送失败",
	             readOnly : true,
	             border : false,
	             itemId : "fail_info",
	             hidden : true
	         }
	];
    
    // 表单按钮
    var formButtons = [
	           {
	               text : "推送",
	               handler : function() {
	        	   if (form_panel.getForm().isValid()) {
    	        	   form_panel.getForm().submit({
    	        	       url: "/QuickLifeServer/WebPushMessageAction",
    	        	       method: "POST",
    	        	       waitTitle:"请稍候",
    	        	       waitMsg:"正在请求推送优惠。。。",
    	        	       params: {
    	        		   actionflag: "addmsg",
    	        		   busid: Ext.getDom("id").value,
    	        		   cpid: record.get("id"),
    	        		   overdue: record.get("end_time"),
    	        		   type : record.get("type"),
    	        		   area : record.get("area")
    	        	       },
    	        	       success: function(form, action) {
    	        		   var rt = Ext.decode(action.response.responseText);
    	        		   if (rt.result == "SUCCESS") {
    	        		       push_dialog.close();
    	        		   } else {
    	        		       Ext.ComponentQuery.query("#fail_info")[0].setValue(rt.rtinfos).setVisible(true);
    	        		   }
    	        	       },
    	        	       failure: function(form, action) {
    	        		   var rt = JSON.parse(action.response.responseText);
 	        		   if (rt.result == "SUCCESS") {
 	        		      push_dialog.close();
 	        		   } else {
 	        		       Ext.ComponentQuery.query("#fail_info")[0].setValue(rt.rtinfos).setVisible(true);
 	        		   }
    	        	       }
    	        	   });
    	               }
	               }
	           }
	        ];
    // 实例化表单
    var form_panel = Ext.create("Ext.form.Panel", {
	width: 300,
	height: 150,
	url: "/QuickLifeServer/WebCouponManageAction",
	method: "POST",
	layout : {
	   type : 'vbox',
	   pack : "Even",
	   align : "center"
	},
	renderTo : Ext.getBody(),
	defaultType : 'textfield',
	defaults : {
	    width : "90%",
	    style : {
		marginTop : "10px"
	    }
	},
	items : formItems,
	buttons : formButtons
    });
    // 弹出窗实例化
    var push_dialog = Ext.create('Ext.window.Window', {
	title : "推送优惠",
	modal: true,
	width: 300, 
	height: 240,
	layout : "fit",
	shadow : "drop",
	shadowOffset : 30,
	items : form_panel
    });
    // 显示弹出窗
    push_dialog.show();
}